package org.argus.common.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.argus.common.core.token.ITokenManager;
import org.argus.common.mybatis.base.BaseDomainEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author 刘文/Cliff Liu
 * @Date 2024/7/20
 */
@Component
public class InsertUpdateMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private ITokenManager tokenManager;

    /**
     * 使用mp实现添加操作,这个方法会执行,metaObject元数据(表中的名字,表中的字段)
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        //根据名称设置属性值
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createdBy", Long.class, tokenManager.getUserId());
        this.strictInsertFill(metaObject, "updatedBy", Long.class, tokenManager.getUserId());

        // domainId 设置
        Object originalObject = metaObject.getOriginalObject();
        // 没有明确设定domainId,取当前用户关联的domainId
        if (originalObject instanceof BaseDomainEntity && ((BaseDomainEntity) originalObject).getDomainId() == null) {
//            ((BaseDomainEntity) originalObject).setDomainId(tokenManager.getUserCurrentDomainId());
            this.strictInsertFill(metaObject, "domainId", Long.class, tokenManager.getUserCurrentDomainId());
        }
    }

    /**
     * 使用mp实现修改操作,这个方法会执行
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
        this.strictInsertFill(metaObject, "updatedBy", Long.class, tokenManager.getUserId());
    }
}